<?php
/**********************************************************************************
WIKINDX: Bibliographic Management system.
Copyright (C)

This program is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program;
if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

The WIKINDX Team 2004
sirfragalot@users.sourceforge.net
**********************************************************************************/
/*****
*	RIS export class
*****/
class RIS
{
// Constructor
	function RIS($db)
	{
		$this->db = $db;
		include_once("core/file/FILE.php");
		$this->file = new FILE($this->db);
		include_once("core/template/TEMPLATE.php");
		$this->template = new TEMPLATE('content');
		include_once("core/messages/ERRORS.php");
		$this->errors = new ERRORS();
		include_once("core/messages/MESSAGES.php");
		$this->messages = new MESSAGES();
		include_once("core/session/SESSION.php");
		$this->session = new SESSION();
		include_once("core/cite/CITE.php");
		$this->cite = new CITE($this->db, FALSE);
		include_once("core/file/RISMAP.php");
		$this->map = new RISMAP();
		include_once("core/file/export/EXPORTCOMMON.php");
		$this->common = new EXPORTCOMMON($this->db);
		$this->pString = '';
// Perform some system admin
		$this->file->tidyFiles();
	}
// write $this->pString to file.  If file exists, it is written over.
	function process()
	{
		$this->template->setVar('heading', $this->messages->text("heading", "exportRis"));
		$this->getData();
		list($fileName, $fullFileName) = $this->file->createFileName($this->pString, '.ref');
		if(!$fullFileName)
			$this->failure($this->errors->text("file", "write", ": $fileName"));
		if(!$fp = fopen("$fullFileName", "w"))
			$this->failure($this->errors->text("file", "write", ": $fileName"));
// All data is stored in the database as UTF-8
		if(!fputs($fp, utf8_decode($this->pString)))
			$this->failure($this->errors->text("file", "write", ": $fileName"));
		fclose($fp);
		$this->common->writeFilenameToSession($fileName);
		$pString = $this->common->listFiles();
		$this->template->setVar('body', $pString);
		return $this->template->process();
	}
// get data from database
	function getData()
	{
		if(!$sql = $this->session->getVar('sql_stmt'))
			$this->failure($this->errors->text("file", "noSql"));
		$recordset = $this->db->query(stripslashes($sql));
		$this->pString = '';
// load default arrays
		$this->loadArrays();
		while($row = $this->db->loopRecordSet($recordset))
		{
// Do we need to switch `year1` (publicationYear) and `year2` (reprintYear)
			if((($row['type'] == 'book') || ($row['type'] == 'book_article'))
				&& $row['year1'] && $row['year2'])
				$row['year1'] = $row['year2'];
// else, always use `year2` in preference to `year1` except for web_article, database, 
// proceedings and proceedings_article
			else if($row['year2'] && ($row['type'] != 'web_article') && 
			($row['type'] != 'proceedings_article') && ($row['type'] != 'proceedings') && 
			($row['type'] != 'database'))
			{
				$row['year1'] = $row['year2'];
				unset($row['year2']);
			}
			$entryArray = array();
			$entryArray[] = 'TY  - ' . $this->map->types[$row['type']];
			$entryArray[] = 'T1  - ' .  $this->common->titleFormat($row);
			foreach($this->map->{$row['type']}['resource_creator'] as $wkField => $risField)
			{
				if(!$creators = $this->nameFormat($row, $wkField, $risField))
					continue;
				else
					$entryArray[] = $creators;
			}
			foreach($this->map->{$row['type']} as $table => $tableArray)
			{
				if($table == 'resource_creator')
					continue;
				foreach($tableArray as $wkField => $risField)
				{
					if(isset($row[$wkField]) && $row[$wkField])
					{
// asterisk (character 42) is not allowed in the author, keywords, or periodical name fields - replace with '#'
						if($risField == 'JF')
							$entryArray[] = $risField . '  - ' . 
							preg_replace("/\*/", "#", stripslashes($row[$wkField]));
						else if(($risField == 'UR') && (($row['type'] == 'web_article') || 
							($row['type'] == 'database')) && 
							($item = $this->webFormat($row)))
							$entryArray[] = $item;
						else
							$entryArray[] = $risField . '  - ' . 
							stripslashes($row[$wkField]);
					}
				}
			}
			if($item = $this->year1Format($row))
				$entryArray[] = 'PY  - ' . $item;
			if(isset($row['year2']) && $row['year2'] && (($row['type'] == 'proceedings') || 
				($row['type'] == 'proceedings_article')) && ($item = $this->year2Format($row)))
				$entryArray[] = $item;
			if($row['miscField4'] && (($row['type'] == 'film') || ($row['type'] == 'broadcast'))
				&& ($item = $this->timeFormat($row)))
				$entryArray[] = $item;
// RefMan doesn't like pages on some types
			if(($row['type'] != 'hearing') && ($row['type'] != 'unpublished'))
			{
				if($item = $this->common->pageFormat($row, 'ris'))
					$entryArray[] = $item;
			}
			if($item = $this->common->keywordFormat($row, 'ris'))
// 'KW  - ' added to each keyword in $this->common->keywordFormat()
				$entryArray[] = $item;
			if($item = $this->common->grabAbstract($row, 'ris'))
				$entryArray[] = 'N2  - ' . $item;
			if($item = $this->common->grabNote($row, 'ris'))
				$entryArray[] = 'N1  - ' . $item;
			$this->pString .= join("\r", $entryArray) . "\r" . "ER  - \r\r";
		}
	}
// format names.
	function nameFormat($row, $type, $risField)
	{
		if(!$row[$type])
			return '';
		$creatorIds = explode(",", $row[$type]);
		foreach($creatorIds as $id)
			$condition[] = $this->db->formatField('id') . "=" . $this->db->tidyInput($id);
		$recordset = $this->db->select(array('WKX_creator'), 
			array('surname', 'firstname', 'initials', 'prefix', 'id'), 
			" WHERE " . implode(' OR ', $condition));
		while($creatorRow = $this->db->loopRecordSet($recordset))
		{
			$name = $this->common->formatName($creatorRow, 'ris');
			if($name)
// asterisk (character 42) is not allowed in the author, keywords, or periodical name fields - replace with '#'
				$mapName[$creatorRow['id']] = $risField . '  - ' . preg_replace("/\*/", "#", $name);
		}
		foreach($creatorIds as $id)
			$nameArray[] = $mapName[$id];
		if(!isset($nameArray) || empty($nameArray))
			return '';
		return join("\r", $nameArray);
	}
// web_article,  URL and accessed date
	function webFormat($row)
	{
		$url = $year = $month = $day = FALSE;
		$url = "L2  - " . stripslashes($row['url']);
		if($row['year2'])
			$year = stripslashes($row['year2']);
		if($row['miscField3'])
			$month = $row['miscField3'] < 10 ? '0' . $row['miscField3'] : $row['miscField3'];
		if($row['miscField2'])
			$day = $row['miscField2'] < 10 ? '0' . $row['miscField2'] : $row['miscField2'];
		return $url . "\r" . "Y2  - " . $year . '/' . $month . '/' . $day . '/';
	}
// format YYYY/MM/DD of conference dates etc.
	function year2Format($row)
	{
		$year = $month = $day = FALSE;
		$year = stripslashes($row['year2']);
		if($row['miscField3'])
			$month = $row['miscField3'] < 10 ? '0' . $row['miscField3'] : $row['miscField3'];
		if($row['miscField2'])
			$day = $row['miscField2'] < 10 ? '0' . $row['miscField2'] : $row['miscField2'];
		return "Y2  - " . $year . '/' . $month . '/' . $day . '/';
	}
// format YYYY/MM/DD of publication
	function year1Format($row)
	{
		$year = $month = $day = FALSE;
		if($row['year1'])
			$year = stripslashes($row['year1']);
		if(($row['type'] != 'web_article') && ($row['type'] != 'proceedings_article') && 
			($row['type'] != 'proceedings') && ($row['type'] != 'database'))
		{
			if($row['miscField3'])
				$month = $row['miscField3'] < 10 ? '0' . $row['miscField3'] : $row['miscField3'];
			if($row['miscField2'])
				$day = $row['miscField2'] < 10 ? '0' . $row['miscField2'] : $row['miscField2'];
		}
		return $year . '/' . $month . '/' . $day . '/';
	}
// format running time for films
	function timeFormat($row)
	{
		$hours = $minutes = FALSE;
		$hours = stripslashes($row['miscField4']);
		if($row['miscField1'])
			$minutes = $row['miscField1'] < 10 ? '0' . $row['miscField1'] : $row['miscField1'];
		return "M2  - " . $hours . "'" . $minutes . "\"";
	}
// load default arrays
	function loadArrays()
	{
// need to use English constants for RIS
		include_once("languages/en/CONSTANTS.php");
		$constants = new CONSTANTS_en();
		$constants->convertNumbers();
		$this->editionArray = $constants->cardinalToOrdinalWord();
		$this->monthArray = $constants->monthToShortName();
	}
// Error handling
	function failure($error)
	{
		$this->template->setVar('body', $error);
		$pString = $this->template->process();
		include_once("core/html/CLOSE.php");
		new CLOSE($this->db, $pString);
	}
}
?>
